﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using ZXing;
using ZXing.Common;

namespace OpenClientX.Utils
{
    class BarCodeUtil
    {
        /// <summary>
        /// 生成条形码，zebar打印机生成png格式的图像，其他生成bmp
        /// </summary>
        /// <param name="barCode">条形码</param>
        /// <param name="path">保存的路径</param>
        /// <param name="fileFormat">是否生成bmp的格式，true-生成，false-生成其他格式</param>
        /// <returns></returns>
        public static Bitmap CreateBarcode(String barCode, String path, Boolean fileFormat) 
        {
            if (!Directory.Exists("C://MssClientCache//barcodeCache//"))//判断文件夹是否存在 
                Directory.CreateDirectory("C://MssClientCache//barcodeCache//");//不存在则创建文件夹 

            BarcodeWriter writer = new BarcodeWriter();
            //使用ITF 格式，不能被现在常用的支付宝、微信扫出来
            //如果想生成可识别的可以使用 CODE_128 格式
            //writer.Format = BarcodeFormat.ITF;
            writer.Format = BarcodeFormat.CODE_128;
            EncodingOptions options = new EncodingOptions()
            {
                PureBarcode = true,
                Width = 700,
                Height = 100,
                Margin = 2
            };
            writer.Options = options;
            Bitmap bm = writer.Write(barCode);
            bm = KiSetText(bm, barCode);
            if (fileFormat)
            {
                bm.Save("C://MssClientCache//barcodeCache//" + path, ImageFormat.Bmp);
            }
            else
            {
                bm.Save("C://MssClientCache//barcodeCache//" + path, ImageFormat.Png);
            }
            
            return bm;
        }

        /// <summary>
        /// 设置文字
        /// </summary>
        /// <param name="b">原始图片</param>
        /// <param name="txt">显示的文字</param>
        /// <returns>输出后的图片</returns>
        public static Bitmap KiSetText(Bitmap b, string txt)
        {
            if (b == null)
                return null;

            Bitmap resizeImage = new Bitmap(b.Width, b.Height + 40);
            Graphics gfx = Graphics.FromImage(resizeImage);
            gfx.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
            gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, 750, 140));

            gfx.DrawImageUnscaled(b, 0, 0);
            //gfx.MeasureString();
            // 作为演示，我们用Arial字体，大小为32，红色。
            RectangleF layoutRectangle = new RectangleF(0, 107, b.Width, 33);
            FontFamily fm = new FontFamily("Verdana");
            Font font = new Font(fm, 26, FontStyle.Regular, GraphicsUnit.Pixel);
            SolidBrush sb = new SolidBrush(Color.Black);
            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;

            gfx.DrawString(txt, font, sb, layoutRectangle, stringFormat);
            gfx.Dispose();
            return resizeImage;
        }
    }
}
